Why was cyclic enamide 22 formed?

The reaction of 21 to 22 has to take place under acidic conditions. The atoms in the molecule aside from the nitrogen do not have great nucleophilicity and so no other reaction than cyclic formation of the enamide will occur (however, the nucleophilicity of the nitrogen itself is low due to the effect of the carbonyl group next to it). The aldehyde-like methoxonium (shown above) is much more reactive than a normal aldehyde, due to the positive charge. As shown in the 3D structure of the intermediate below, the nitrogen is in very close proximity to the methoxonium ion. Since the atoms are so close, the nitrogen will attack the carbon attached to the oxygen remove the positive charge from the oxygen and form the eight-membered enamide.